import 'package:bot_toast/bot_toast.dart';
import 'package:client_wifi/pages/home/view.dart';
import 'package:flutter/material.dart';
import 'package:wifi_plugin/wifi_plugin.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({super.key});
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'WiFi',
      home: WiFiHomePage(),
      debugShowCheckedModeBanner: false,
      builder: BotToastInit(), //1. call BotToastInit
      navigatorObservers: [BotToastNavigatorObserver()],
    );
  }
}

class WiFiHomePage extends StatefulWidget {
  const WiFiHomePage({super.key});
  @override
  State<WiFiHomePage> createState() => _WiFiHomePageState();
}

class _WiFiHomePageState extends State<WiFiHomePage> {
  List<WifiNetwork> _wifiList = [];
  bool _busy = false;
  String? _connectedSSID;

  Future<void> _scan() async {
    setState(() => _busy = true);
    try {
      final list = await WifiPlugin.scanNetworks();
      setState(() => _wifiList = list);
    } catch (e) {
      debugPrint('scan error: $e');
      if (mounted) {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(const SnackBar(content: Text('扫描失败')));
      }
    } finally {
      if (mounted) setState(() => _busy = false);
    }
  }

  Future<void> _onTapNetwork(WifiNetwork net) async {
    String? password;
    if (!net.isOpen) {
      password = await _askPassword(context, net.ssid);
      if (password == null) return; // 取消
      Navigator.push(
        context,
        MaterialPageRoute(
          builder: (context) => HomePage(wifi: net, pwd: password ?? ''),
        ),
      );
    }
    // setState(() => _busy = true);
    // final ok = await WifiPlugin.connect(ssid: net.ssid, password: password);
    // if (!mounted) return;
    // setState(() => _busy = false);
    // if (ok) {
    //   setState(() => _connectedSSID = net.ssid);
    //   ScaffoldMessenger.of(
    //     context,
    //   ).showSnackBar(SnackBar(content: Text('已连接 ${net.ssid}')));
    // } else {
    //   ScaffoldMessenger.of(
    //     context,
    //   ).showSnackBar(SnackBar(content: Text('连接 ${net.ssid} 失败')));
    // }
  }

  Future<String?> _askPassword(BuildContext ctx, String ssid) async {
    final ctrl = TextEditingController();
    return showDialog<String>(
      context: ctx,
      builder: (context) {
        return AlertDialog(
          title: Text('wifi名:$ssid'),
          content: TextField(
            controller: ctrl,
            obscureText: true,
            decoration: const InputDecoration(
              labelText: '密码',
              hintText: '输入 Wi‑Fi 密码',
            ),
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.pop(context),
              child: const Text('取消'),
            ),
            ElevatedButton(
              onPressed: () => Navigator.pop(context, ctrl.text),
              child: const Text('下一步'),
            ),
          ],
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('选择 WIFI')),
      body: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                ElevatedButton(
                  onPressed: _busy ? null : _scan,
                  child: const Text('扫描附近WiFi网络'),
                ),
                const SizedBox(width: 12),
                if (_connectedSSID != null) Text('已连接: $_connectedSSID'),
              ],
            ),
            const SizedBox(height: 16),
            Expanded(
              child: _wifiList.isEmpty
                  ? const Text('尚未扫描到任何WiFi网络')
                  : ListView.separated(
                      itemCount: _wifiList.length,
                      separatorBuilder: (_, __) => const Divider(height: 1),
                      itemBuilder: (_, i) {
                        final w = _wifiList[i];
                        return ListTile(
                          leading: Icon(w.isOpen ? Icons.wifi : Icons.lock),
                          title: Text(w.ssid),
                          subtitle: Text(
                            '${w.isOpen ? '开放网络' : '需密码'}  · RSSI ${w.rssi}',
                          ),
                          onTap: _busy ? null : () => _onTapNetwork(w),
                        );
                      },
                    ),
            ),
          ],
        ),
      ),
    );
  }
}
